package com.sunwayworld.basemodule.business.qualitycontrol.qualitycontrolplan.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sunwayworld.basemodule.business.qualitycontrol.qualitycontrolplan.bean.LimsQualitycontrolplanBean;
import com.sunwayworld.basemodule.business.qualitycontrol.qualitycontrolplan.bean.LimsQualitycontrolplanProjectBean;
import com.sunwayworld.basemodule.business.qualitycontrol.qualitycontrolplan.dao.LimsQualitycontrolplanDao;
import com.sunwayworld.basemodule.business.qualitycontrol.qualitycontrolplan.service.LimsQualitycontrolplanProjectService;
import com.sunwayworld.basemodule.business.qualitycontrol.qualitycontrolplan.service.LimsQualitycontrolplanService;
import com.sunwayworld.basemodule.business.qualitycontrol.qualitycontrolresult.bean.LimsQualitycontrolTestResultBean;
import com.sunwayworld.basemodule.business.qualitycontrol.qualitycontrolresult.service.LimsQualitycontrolTestResultService;
import com.sunwayworld.framework.at.annotation.AuditTrailEntry;
import com.sunwayworld.framework.at.annotation.AuditTrailType;
import com.sunwayworld.framework.context.ApplicationContextHelper;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.restful.data.RestJsonWrapperBean;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Repository
@GikamBean
public class LimsQualitycontrolplanServiceImpl implements LimsQualitycontrolplanService {

    @Autowired
    private LimsQualitycontrolplanDao limsQualitycontrolplanDao;

    @Override
    @SuppressWarnings("unchecked")
    public LimsQualitycontrolplanDao getDao() {
        return limsQualitycontrolplanDao;
    }

    @Autowired
    private LimsQualitycontrolplanProjectService limsQualitycontrolplanProjectService;

    @Autowired
    @Lazy
    private LimsQualitycontrolTestResultService limsQualitycontrolTestResultService;

    @Override
    @Transactional
    @AuditTrailEntry(AuditTrailType.INSERT)
    public Long insert(RestJsonWrapperBean jsonWrapper) {
        LimsQualitycontrolplanBean limsQualitycontrolplan = jsonWrapper.parseUnique(LimsQualitycontrolplanBean.class);
        limsQualitycontrolplan.setId(ApplicationContextHelper.getNextIdentity());
        limsQualitycontrolplan.setActiveStatus("on");
        limsQualitycontrolplan.setPlanCode(ApplicationContextHelper.getNextSequence(getDao().getTable()));

        //质控物新增时检测到该质控物同水平已存在且激活，就把已存在的禁用掉，保证一个质控物一个水平同一时刻只有一个激活的
        //暂时注释掉，逻辑尚待补充
//        List<LimsQualitycontrolplanBean> oldPlans = this.selectListByFilter(SearchFilter.instance()
//                .match("controlMaterialId", limsQualitycontrolplan.getControlMaterialId()).filter(MatchPattern.EQ)
//                .match("controlMaterialLevel", limsQualitycontrolplan.getControlMaterialLevel()).filter(MatchPattern.EQ));
//        if (!oldPlans.isEmpty()) {
//            oldPlans.forEach(i -> {
//                i.setActiveStatus("off");
//            });
//            getDao().update(oldPlans, "activeStatus");
//        }

        getDao().insert(limsQualitycontrolplan);
        return limsQualitycontrolplan.getId();
    }

    @Override
    public JSONObject checkIfStillInUse(RestJsonWrapperBean jsonWrapperBean) {
        String gridType = jsonWrapperBean.getParamValue("gridType");
        if (gridType == null || "planGrid".equals(gridType)) {
            List<LimsQualitycontrolplanBean> plans = jsonWrapperBean.parse(LimsQualitycontrolplanBean.class);
            List<Long> planIds = plans.stream().map(LimsQualitycontrolplanBean::getId).collect(Collectors.toList());
            List<LimsQualitycontrolplanProjectBean> projects = limsQualitycontrolplanProjectService.selectListByFilter(SearchFilter.instance().match("planId", planIds).filter(MatchPattern.OR));

            if (projects.isEmpty()) {
                JSONObject req = new JSONObject();
                req.put("flag", false);
                return req;
            }
            return checkIfProjectStillInUse(projects);
        } else {
            List<LimsQualitycontrolplanProjectBean> projects = jsonWrapperBean.parse(LimsQualitycontrolplanProjectBean.class);
            return checkIfProjectStillInUse(projects);
        }
    }

    public JSONObject checkIfProjectStillInUse(List<LimsQualitycontrolplanProjectBean> projectBeans) {
        JSONObject req = new JSONObject();
        StringBuffer message = new StringBuffer();
        boolean flag = false;

        projectBeans.forEach(i -> {
            LimsQualitycontrolTestResultBean first = limsQualitycontrolTestResultService.selectFirstByFilter(SearchFilter.instance().match("controlProjectId", i.getId()).filter(MatchPattern.EQ));
            if (first != null) {
                message.append(i.getProductCode()).append("-").append(i.getProductName()).append("<br/>");
            }
        });

        if (message.length() > 0) {
//            message.insert(0, I18nHelper.getMessage("QUALITY_CONTROL.PLANPROJECT.CANNOT_DELETE") + "<br/>");
            flag = true;
        }
        req.put("flag", flag);
        req.put("message", message);

        return req;
    }
}
